package common.wx;

import java.security.MessageDigest;
import java.util.Date;

import net.sf.json.JSONObject;
import common.impl.CreateRandomCode;
import common.impl.MicroBlog;

import weibo4j.model.PostParameter;

public class WxJsAPI {

	private static final String URL_GET_ACCESSTOKEN = "https://api.weixin.qq.com/cgi-bin/token";
	private static final String GRANT_TYPE = "client_credential";
	private static final String URL_GETTICKET = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";
	private static final String TYPE = "jsapi";
	private static String TICKET = null;
	private static long GET_TIME;

	public static String getConfig(String url, String signType) throws Exception {
		JSONObject jo = new JSONObject();
		long current = new Date().getTime();
		if (GET_TIME == 0 || current - GET_TIME > 7000000) {
			String r1 = MicroBlog
					.post(
							URL_GET_ACCESSTOKEN,
							new PostParameter[] {
									new PostParameter("appid",
											WxConfig.wx_appid),
									new PostParameter("grant_type", GRANT_TYPE),
									new PostParameter("secret",
											WxConfig.wx_appsecret) });
			JSONObject jo1 = JSONObject.fromObject(r1);
			if (null != jo1) {
				if (jo1.containsKey("access_token")) {
					String accessToken = jo1.getString("access_token");
					String r2 = MicroBlog.post(URL_GETTICKET,
							new PostParameter[] {
									new PostParameter("access_token",
											accessToken),
									new PostParameter("type", TYPE) });
					JSONObject jo2 = JSONObject.fromObject(r2);
					if (null != jo2) {
						if (jo2.containsKey("ticket")) {
							TICKET = jo2.getString("ticket");
							GET_TIME = new Date().getTime();
						}
					}
				}
			}
		}
		if (null != TICKET) {
			String noncestr = CreateRandomCode.getRandomString(16);
			long timestamp = new Date().getTime() / 1000;
			String s1 = "jsapi_ticket=" + TICKET + "&noncestr=" + noncestr
					+ "&timestamp=" + timestamp + "&url=" + url;
			if(!"MD5".equals(signType))
				signType = "SHA-1";
			MessageDigest md = MessageDigest.getInstance(signType);
			String signature = byteToStr(md.digest(s1.getBytes("utf-8")))
					.toLowerCase();
			jo.put("noncestr", noncestr);
			jo.put("timestamp", timestamp);
			jo.put("signature", signature);
		}
		return jo.toString();
	}

	/**
	 * 将字节数组转换为十六进制字符串
	 * 
	 * @param byteArray
	 * @return
	 */
	private static String byteToStr(byte[] byteArray) {
		String strDigest = "";
		for (int i = 0; i < byteArray.length; i++) {
			strDigest += byteToHexStr(byteArray[i]);
		}
		return strDigest;
	}

	/**
	 * 将字节转换为十六进制字符串
	 * 
	 * @param mByte
	 * @return
	 */
	private static String byteToHexStr(byte mByte) {
		char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
				'B', 'C', 'D', 'E', 'F' };
		char[] tempArr = new char[2];
		tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
		tempArr[1] = Digit[mByte & 0X0F];

		String s = new String(tempArr);
		return s;
	}

}
